<template>
	<div class="multiple-select-wrapper">
		<!-- 信息汇总节点选择 -->
		<el-form-item :label="label" :prop="prop" :required="required" label-width="120px" v-if="prop === 'summary'">
			<el-select v-model="values" :disabled="showDetail" multiple value-key="node" placeholder="请选择要汇总的AI流程节点" @change="onChange">
				<el-option v-for="item in options" :key="item.node" :label="item.name" :value="item"> </el-option>
			</el-select>
		</el-form-item>
		<!-- 变量多选 -->
		<el-form-item :label="label" :prop="prop !== 'wordsVariable' ? prop : ''" :required="required" label-width="120px" v-else-if="prop === 'wordsVariable'" class="varible-summary-select">
			<el-select :value="getSelectedTextList()" multiple value-key="node-variable" placeholder="请选择要推送的变量" class="varible-summary-select-select" @remove-tag="onRemoveTag">
				<el-tabs v-model="activeName" @tab-click="handleClick" class="varible-summary-customer-text">
					<el-tab-pane label="客户信息" name="customer" class="customer-box">
						<div class="varible-summary-role-box">
							<p class="role-text">角色：</p>
							<el-tag v-for="item in roleData" :key="item.id" class="role-tag" :class="{ activeTag: activeTag === item.id }" @click="checkRole(item.id)">{{ item.name }}</el-tag>
						</div>
						<el-option v-for="item in getVariablesByRole()" :key="item.id" :label="item.id">
							<div class="label" :class="selectedValues.includes(item.id) ? 'select' : ''" @click="onVariable(item)">{{ item.name }}</div>
						</el-option>
					</el-tab-pane>
					<el-tab-pane label="业务信息" name="business">
						<el-option v-for="item in businessData" :key="item.id" :label="item.id">
							<div class="label" :class="selectedValues.includes(item.id) ? 'select' : ''" @click="onBizVariable(item)">{{ item.name }}</div>
						</el-option>
					</el-tab-pane>
				</el-tabs>
			</el-select>
		</el-form-item>
		<!-- 其他多选 -->
		<el-form-item :label="label" :prop="prop" :required="required" label-width="120px" v-else>
			<el-select v-model="values" :disabled="showDetail" multiple value-key="node" placeholder="请选择要推送的内容" @change="onChange">
				<el-option v-for="item in options" :key="item.value" :label="item.name" :value="item"> </el-option>
			</el-select>
		</el-form-item>
	</div>
</template>

<script>
import { getAllRole, getBusinessInitModeVaribles, getVariablesAll } from '@/api/api.js';

export default {
	props: {
		label: {
			type: String,
			default: () => ''
		},
		prop: {
			type: String,
			required: true,
			default: () => ''
		},
		required: {
			type: Boolean,
			default: () => false
		},
		value: {
			type: Array,
			required: true,
			default: () => []
		},
		notifyExternal: {
			type: Object,
			default: () => {}
		},
		options: {
			type: Array,
			required: false,
			default: () => []
		},
		showDetail: {
			type: Boolean,
			default: () => false
		},
		taskId: {
			type: String,
			required: true,
			default: () => ''
		}
	},
	data() {
		return {
			values: [], // 选中的内容
			variableOptions: [],
			variableValues: [],
			roleData: [],
			activeName: 'customer',
			activeTag: 1,
			scenId: JSON.parse(sessionStorage.getItem('sceneData'))?.id || this.$route.params.scenId,
			pageData: {
				page: 1,
				pageSize: 100000,
				total: 0
			},
			businessData: [],
			selectedValues: [] // 已选择的变量名
		};
	},

	watch: {
		value(val) {
			this.$nextTick(() => {
				if (val && val.length > 0) {
					this.values = [...val];
					console.log(this.value, this.values, 'values:');
				} else {
					this.values = [];
				}
				// this.initAllRole();
				this.parseInValue();
				// this.initBusinessData();
			});
		},
		notifyExternal: {
			handler(val) {
				console.log('notifyExternal', val);
				if (val && val.params) {
					const { params = [] } = val;
					this.variableValues = [];
					params?.forEach(item => {
						this.variableValues.push(item.select);
					});
				}
			},
			deep: true
		}
	},
	mounted() {
		console.warn('value ', this.value);
		this.$nextTick(() => {
			if (this.value && this.value.length > 0) {
				this.values = [...this.value];
				console.log(this.value, this.values, 'values:');
			}
			if (this.prop === 'summary') {
				// return;
			}
			// 获取存储的变量
			console.warn(this.notifyExternal, 'notifyExternal');
			const { params = [] } = this.notifyExternal;
			params?.forEach(item => {
				this.variableValues.push(item.select);
			});
			// if (this.notifyExternal?.params) {
			// 	this.variableValues = this.notifyExternal.params;
			// }
			this.initAllRole();
			this.initBusinessData();
		});
		console.log('##multiple select view', this.value, this.options, this.prop, this.required);
	},
	methods: {
		onChange(value) {
			console.log('###value', this.value, this.values, value, this.variableValues);
			console.warn(this.values, 'value:', value);
			if (this.prop === 'wordsVariable') {
				let resultValues = [];
				console.warn(this.activeName, 'activeName');
				if (this.activeName === 'customer') {
					this.variableValues.forEach(itemId => {
						let result = this.variableOptions.filter(vItem => {
							console.log(vItem, itemId);
							return vItem.id === itemId;
						});
						if (result && result.length > 0) {
							resultValues = [...resultValues, result[0]];
						}
					});
					this.$emit('input', this.prop, resultValues);
				}
				if (this.activeName === 'business') {
					this.variableValues.forEach(itemId => {
						let result = this.businessData.filter(vItem => {
							return vItem.id === itemId;
						});
						if (result && result.length > 0) {
							resultValues = [...resultValues, result[0]];
						}
					});
					this.$emit('input', this.prop, resultValues);
				}
			} else {
				this.$emit('input', this.prop, this.values);
			}
		},

		// 初始化所有角色
		initAllRole() {
			getAllRole(this.scenId)
				.then(res => {
					this.roleData = res.data.data;
					this.activeTag = res.data.data[0]?.id;
					// if (this.activeTag) {
					// 	this.initcustomerData(this.activeTag);
					// }
					this.getVariablesAll();
				})
				.catch(err => {
					console.log(err);
				});
		},
		getVariablesAll() {
			let param = {
				scenId: this.scenId,
				page: 1,
				pageSize: 10000
			};
			this.variableOptions = [];
			getVariablesAll(param)
				.then(res => {
					if (res.data.data && res.data.data.rows) {
						res.data.data.rows.map(item => {
							if (item.roleId && item.initMode === 'user-data') {
								const data = {
									id: item.id,
									name: item.name,
									roleId: item.roleId,
									dataMasking: item.dataMasking,
									params: item.params,
									url: item.url,
									method: item.method,
									linkedKey: item.linkedKey,
									isDefault: item.isDefault,
									key: item.name,
									property: item.type,
									content: '',
									initMode: item.initMode,
									scenId: this.scenId,
									roleName: item.bizscenario_role.name,
									isDisabled: item.isDisabled
								};
								this.variableOptions.push(data);
							}
						});
						this.pageData.total = res.data.data.count;
						this.parseInValue();
					} else {
						console.warn('get variable list error ', res.data);
					}
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},
		getVariablesByRole() {
			return this.variableOptions.filter(item => item.roleId === this.activeTag);
		},
		// 客户信息变量配置初始化
		initBusinessData() {
			let data = {
				scenId: this.scenId,
				initMode: 'user-data'
			};
			getBusinessInitModeVaribles(data)
				.then(res => {
					console.log(res.data.data, '业务信息变量');
					this.businessData = res.data.data.data;
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},
		checkRole(id) {
			this.activeTag = id;
		},
		onVariable(value) {
			if (this.selectedValues.includes(value.id)) {
				this.removeSelectVariable(value.id);
			} else {
				this.selectedValues.push(value.id);
			}
			this.onVariableChange();
		},
		onBizVariable(value) {
			if (this.selectedValues.includes(value.id)) {
				this.removeSelectVariable(value.id);
			} else {
				this.selectedValues.push(value.id);
			}
			this.onVariableChange();
		},
		removeSelectVariable(vid) {
			const index = this.selectedValues.indexOf(vid);
			if (index >= 0) {
				this.selectedValues.splice(index, 1);
			}
		},
		onRemoveTag(value) {
			// 客户信息 业务信息
			if (value.includes('客户信息')) {
				for (const item of this.variableOptions) {
					const text = `客户信息-${item.roleName}-${item.name}`;
					if (value === text) {
						this.removeSelectVariable(item.id);
						break;
					}
				}
			} else if (value.includes('业务信息')) {
				for (const item of this.businessData) {
					const text = `业务信息-${item.name}`;
					if (value === text) {
						this.removeSelectVariable(item.id);
						break;
					}
				}
			}

			this.onVariableChange();
		},
		getSelectedTextList() {
			let list = [];
			this.selectedValues.map(id => {
				for (const item of this.variableOptions) {
					if (id === item.id) {
						list.push(`客户信息-${item.roleName}-${item.name}`);
						break;
					}
				}
				for (const item of this.businessData) {
					if (id === item.id) {
						list.push(`业务信息-${item.name}`);
						break;
					}
				}
			});

			return list;
		},
		onVariableChange() {
			let list = [];
			this.selectedValues.map(id => {
				for (const item of this.variableOptions) {
					if (id === item.id) {
						list.push(item);
						break;
					}
				}
				for (const item of this.businessData) {
					if (id === item.id) {
						list.push(item);
						break;
					}
				}
			});

			this.$emit('input', 'wordsVariable', list);
		},
		parseInValue() {
			this.selectedValues = [];
			if (this.value) {
				this.value.map(data => {
					for (const item of this.variableOptions) {
						if (data.id === item.id) {
							this.selectedValues.push(item.id);
							break;
						}
					}
					for (const item of this.businessData) {
						if (data.id === item.id) {
							this.selectedValues.push(item.id);
							break;
						}
					}
				});
			}
		}
	}
};
</script>

<style lang="less" scoped>
.el-select {
	width: calc(100% - 54px);
}
.varible-summary-customer-text {
	.varible-summary-role-box {
		display: flex;
		.role-text {
			font-size: 13px;
			font-family: PingFang SC;
			font-weight: 400;
			color: #999999;
		}
		.role-tag {
			height: 32px;
			background: #ffffff;
			border-radius: 4px;
			color: #6784f2;
			border: 1px solid #c9def8;
			margin: 0 7px;
			cursor: pointer;
		}
		.activeTag {
			height: 32px;
			border-radius: 4px;
			background-color: #e7f2fe;
			border: 1px solid #c9def8;
			color: #5374f2;
			margin: 0 7px;
			cursor: pointer;
		}
	}
	/deep/ .el-tabs__nav-wrap::after {
		background-color: none !important;
		position: relative;
		height: 0;
	}
	.label {
		width: 100%;
		color: #606266;
		font-weight: 400;
	}
	.select {
		color: #409eff;
		font-weight: 700;
	}
}
</style>
<style lang="less">
.varible-summary-customer-text {
	margin-left: 17px;
}

.varible-summary-customer-text .el-tabs__active-bar {
	background-color: #6384fe !important;
	width: 56px !important;
}
.varible-summary-customer-text .el-tabs__item {
	font-size: 15px;
	font-family: PingFang SC;
	font-weight: 400;
	color: #b7b7b7 !important;
}
.varible-summary-customer-text .el-tabs__item.is-active {
	color: #6384fe !important;
}

.varible-summary-customer-text .el-tabs__nav-wrap::after {
	background-color: none !important;
	position: relative;
	height: 0;
}
</style>
